<template>
  <div>
    <!-- 面包屑导航 -->
    <div class="page_top">
      <div
        class="left_btn"
        @click="back"
      >
        <img
          src="../../assets/image/back.png"
          alt=""
        />
      </div>
      <crumbs
        basetitle="客户"
        title="客户分配"
      ></crumbs>
    </div>
    <div class="content">
      <el-card>
        <filterComponent
          v-model:filter-data="filterData"
          @doSearch="handleSearch"
        />
      </el-card>
      <el-card style="margin-top: 16px">
        <div class="table-list">
          <el-table
            :data="tableData"
            ref="multipleTableRef"
            @sort-change="sort_changeone"
            style="width: 100%"
            :header-cell-style="{
                background: '#FAFAFC',
                color: '#202536',
              }"
          >
            <el-table-column
              prop="date"
              label="客户名"
              align="center"
              min-width="200"
            >
              <template #default="scope">
                <div>
                  {{ scope.row.companyName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="adminName"
              label="超级管理员"
              align="center"
              width="200"
            >
            </el-table-column>
            <el-table-column
              prop="productType"
              label="产品类型"
              align="center"
              width="200"
            >
              <template #default='scope'>
                <div v-if="scope.row.productType===0">子弹发薪</div>
                <div v-if="scope.row.productType===1">电子签</div>
                <div v-if="scope.row.productType===2">日日保</div>
                <div v-if="scope.row.productType===3">长期保</div>
                <div v-if="scope.row.productType===4">微聘</div>
                <div v-if="scope.row.productType===5">微保</div>
                <div v-if="scope.row.productType===6">团意日保</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="salesName"
              label="商务负责人"
              align="center"
              width="200"
            ></el-table-column>
            <el-table-column
              prop="productOpenTime"
              label="开通时间"
              align="center"
              width="200"
              sortable
            >
              <template #default='scope'>
                <div>
                  {{dayjs(scope.row.productOpenTime ).format('YYYY-MM-DD')}}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="updateSalerTime"
              label="最后修改负责人时间"
              align="center"
              width="200"
            >
              <template #default='scope'>
                <div>
                  {{scope.row.updateSalerTime!==null?dayjs(scope.row.updateSalerTime).format('YYYY-MM-DD'):'--'}}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="230"
              align="center"
            >
              <template #default="scope">
                <el-button
                  link
                  style="color: #0256ff"
                  size="small"
                  v-if="scope.row.hasSale===1"
                  @click="change(scope.row)"
                >
                  修改
                </el-button>
                <el-button
                  link
                  style="color: #0256ff"
                  size="small"
                  v-if="scope.row.hasSale===0"
                  @click="fenpei(scope.row)"
                >
                  分配
                </el-button>
                <el-button
                  link
                  style="color: #0256ff"
                  size="small"
                  @click.prevent="detail(scope.row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            :total="pageInfo.total"
            :currentPage="pageInfo.pageNum"
            :pageSize="pageInfo.pageSize"
            @SizeChange="handleSizeChange"
            @CurrentChange="handleCurrentChange"
          ></pagination>
        </div>
      </el-card>
    </div>
    <!-- 分配商务、选择商务 -->
    <el-dialog
      v-model="dialogTableVisible"
      :title="title"
      width="500"
    >
      <div class="flex">
        <p>选择商务：</p>
        <el-cascader
          @change="changevalue"
          v-model="saleId"
          :show-all-levels="false"
          placeholder="请选择"
          :options="options"
          filterable
          :props="props"
        />
      </div>
      <div class="flexcenterbox mt-20">
        <el-button
          type="primary"
          @click="changesure"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script setup lang="ts">
import { getDealList, getProductList } from '../../api/clients/signClient'
import {
  getdepartmentapic,
  changemarketapi,
  setmarketapi,
} from '../../api/api'
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ElMessage,
  ElMessageBox,
  ElTable,
  UploadFile,
  UploadFiles,
  UploadRawFile,
} from 'element-plus'
import dayjs from 'dayjs'
import { log } from 'console'
const router = useRouter()
const route = useRoute()
const title = ref('分配商务')
const dialogTableVisible = ref(false)
onMounted(() => {
  getList()
  getdepartment()
})
const changesure = () => {
  console.log(saleId.value)
  if (saleId.value.length === 0) {
    ElMessage({
      type: 'error',
      message: '请选择商务',
    })
    return
  }
  if (title.value === '分配商务') {
    setmarketapi({
      companyId: companyId.value,
      id: dealId.value,
      productType: productType.value,
      saleId: saleId.value[saleId.value.length - 1],
      serviceStartTime: dayjs().format('YYYY-MM') + '-01',
      serviceState: 0,
    }).then((res: any) => {
      console.log(res)
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        getList()
        dialogTableVisible.value = false
      }
    })
  } else {
    changemarketapi({
      companyId: companyId.value,
      id: dealId.value,
      productType: productType.value,
      saleId: saleId.value[saleId.value.length - 1],
      saleOldId: saleOldId.value,
      serviceStartTime: dayjs().format('YYYY-MM') + '-01',
      serviceState: 0,
    }).then((res: any) => {
      console.log(res)
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        getList()
        dialogTableVisible.value = false
      }
    })
  }
}
const saleOldId = ref<any>(null)
const companyId = ref<any>(null)
const dealId = ref<any>(null)
const productType = ref<any>(null)
const fenpei = (val: any) => {
  saleId.value = []
  dialogTableVisible.value = true
  title.value = '分配商务'
  companyId.value = val.companyId
  dealId.value = val.id
  productType.value = val.productType
}
const change = (val: any) => {
  saleId.value = [val.deptId, val.saleId]
  console.log(saleId.value)
  dialogTableVisible.value = true
  title.value = '修改商务'
  companyId.value = val.companyId
  dealId.value = val.id
  productType.value = val.productType
  saleOldId.value = val.saleId
}
const changevalue = (val: any) => {
  console.log(val)
  console.log(saleId.value[saleId.value.length - 1])
}
const saleId = ref<any>([])
const props = {
  expandTrigger: 'hover' as const,
  label: 'saleName',
  children: 'children',
  value: 'saleId',
}
const options = ref<any>([])
const getdepartment = () => {
  getdepartmentapic().then((res: any) => {
    console.log(res, 'hafgasuy')
    var keyMap = {
      deptId: 'saleId',
      deptName: 'saleName',
    }
    for (var i = 0; i < res.length; i++) {
      var obj = res[i]
      for (var key in obj) {
        var newKey = keyMap[key]
        if (newKey) {
          obj[newKey] = obj[key]
          delete obj[key]
        }
      }
    }
    console.log(res)
    options.value = res
  })
}
const detail = (ele: any) => {
  router.push({ path: '/cockpit', query: { id: ele.companyId } })
}
const handleSearch = () => {
  getList()
}
const getList = () => {
  getDealList({
    ...createQuery(),
    pageNum: pageInfo.value.pageNum,
    pageSize: pageInfo.value.pageSize,
    sortField: sortField.value,
    sortOrder: sortOrder.value,
  }).then((res: any) => {
    tableData.value = res.list
    pageInfo.value.total = res.totalCount
  })
}
const handleCurrentChange = (val: number) => {
  pageInfo.value.pageNum = val
  getList()
}
const handleSizeChange = (val: number) => {
  pageInfo.value.pageSize = val
  getList()
}
const filterData = ref({
  list: {
    companyName: {
      name: '客户名称',
      prop: 'companyName',
      value: '',
      placeholder: '请输入客户名称',
      type: 'input',
      inputType: 'text',
      handleFocus: (item: any) => {},
      handleChange: (item: any) => {},
      handleInput: (item: any) => {},
    },
    productType: {
      name: '产品类型',
      prop: 'productType',
      value: '',
      placeholder: '请选择产品',
      type: 'select',
      options: [],
      defaultAttrs: {
        label: 'dictLabel',
        value: 'dictValue',
      },
      handleFocus: (item: any) => {
        if (item.options?.length) return
        getProductList('crm_product_type').then((res: any) => {
          item.options = res
        })
      },
      handleChange: (item: any) => {},
    },
    hasSale: {
      name: '分配状态',
      prop: 'hasSale',
      value: '',
      placeholder: '请选择',
      type: 'select',
      options: [
        {
          lable: '全部',
          value: '',
        },
        {
          lable: '未分配',
          value: 0,
        },
        {
          lable: '已分配',
          value: 1,
        },
      ],
      defaultAttrs: {
        label: 'lable',
        value: 'value',
      },
      handleFocus: (item: any) => {},
      handleChange: (item: any) => {},
    },
  },
})
const createQuery = () => {
  const data = {}
  for (const key in filterData.value.list) {
    if (typeof filterData.value.list[key].value === 'string') {
      filterData.value.list[key].value =
        filterData.value.list[key].value.trim()
    }
    data[filterData.value.list[key].prop] = filterData.value.list[key].value
  }
  return data
}
const tableData = ref<any>([])
const sort_changeone = (orderInfo: any) => {
  if (orderInfo.order) {
    const map = {
      ascending: 'ASC',
      descending: 'DESC',
    };
    (sortField.value = orderInfo.prop),
      (sortOrder.value = map[orderInfo.order])
  } else {
    sortField.value = null
    sortOrder.value = null
  }
  getList()
}

const sortField = ref('')
const sortOrder = ref('')
const pageInfo = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})
</script>
  
  <style lang="scss" scoped>
.screen_condition {
  box-sizing: border-box;
  padding: 0 20px;
  margin-top: 16px;

  .formbox {
    margin-top: 16px;
    width: 100%;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 30px;
  }
}

.utilsbox {
  display: flex;
  align-items: center;

  .deleate {
    margin-right: 10px;
  }
}
.screen {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  border-bottom: 2px solid #f4f4f7;

  .deleate {
    cursor: pointer;
    display: flex;
    align-items: center;
  }

  .bord {
    font-weight: 700;
  }

  img {
    margin-right: 10px;
    margin-top: 5px;
  }

  .clear {
    color: rgba(148, 151, 177, 1);
    font-size: 14px;
  }
}
.content {
  max-height: 800px;
  overflow: auto;
  box-sizing: border-box;
  margin: 16px;
}
.flex {
  display: flex;
  align-items: center;
}
.mt-20 {
  margin-top: 20px;
}
</style>
  